/**
 * 
 */
package com.android.calldelay;

import java.net.PasswordAuthentication;
import java.util.Calendar;
import java.util.Locale;

import com.android.calldelay.R;

import android.R.integer;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

/**
 * @author ashish
 * 
 */
public class SetUpActivity extends Activity implements OnCheckedChangeListener,
android.view.View.OnClickListener {

	private static final String LOG_TAG = "SetUpActivity";
	private EditText etPassword;
	private CheckBox cbEnablePass;
	private EditText etAlertMin;
	private EditText etAlertSec;
	private CheckBox cbEnableAlert;
	private CheckBox cbOpenSpeaker;
	private RadioButton rbVolumeMaximum;
	private RadioButton rbVolumeMinimum;
	private RadioGroup rgVolume;
	private EditText etSecondsBeforeDialingAgain;
	private EditText etDialingAttempts;
	private EditText etMessage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_page_settings);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		setUpView();
	}

	private void setUpView() {
		Typeface typeface = Typeface.createFromAsset(getAssets(),
				"font/arial.ttf");

		etSecondsBeforeDialingAgain = (EditText) this
				.findViewById(R.id.et_seconds_before_dialing);

		etDialingAttempts = (EditText) this
				.findViewById(R.id.et_dialing_attemptes);

		etSecondsBeforeDialingAgain.setKeyListener(null);
		etSecondsBeforeDialingAgain.setTag("Minutes");
		etSecondsBeforeDialingAgain.setOnClickListener(this);
		etDialingAttempts.setKeyListener(null);
		etDialingAttempts.setTag("Minutes");
		etDialingAttempts.setOnClickListener(this);
		etMessage = (EditText) findViewById(R.id.et_message_sent);
		etPassword = (EditText) findViewById(R.id.et_password);
		etAlertMin = (EditText) findViewById(R.id.et_alert_min);
		etAlertSec = (EditText) findViewById(R.id.et_alert_sec);
		cbEnablePass = (CheckBox) findViewById(R.id.cb_enable_password);
		cbEnableAlert = (CheckBox) findViewById(R.id.cb_enable_alert);
		cbOpenSpeaker = (CheckBox) findViewById(R.id.cb_open_speaker);
		rgVolume = (RadioGroup) findViewById(R.id.radioGroup_spicker);

		rbVolumeMaximum = (RadioButton) findViewById(R.id.cb_volume_maximum);
		rbVolumeMinimum = (RadioButton) findViewById(R.id.cb_volume_minimum);

		Button btnSave = (Button) findViewById(R.id.button_save_settings);
		btnSave.setOnClickListener(this);
		Button btnSetupHome = (Button) findViewById(R.id.button_setup_home);
		btnSetupHome.setOnClickListener(this);

		Button btnSetupWhatis = (Button) findViewById(R.id.button_setup_whatis);
		btnSetupWhatis.setOnClickListener(this);

		cbEnablePass.setChecked(getCheckedState(AppInfo.KEY_PASS_CHECKBOX));
		cbEnableAlert.setChecked(getCheckedState(AppInfo.KEY_ALERT_CHECKBOX));
		cbOpenSpeaker
		.setChecked(getCheckedState(AppInfo.KEY_OPEN_SPEAKER_CHECKBOX));
		// cbVolumeMaximum.setChecked(loadCheckedState(AppInfo.KEY_VOLUME_MAX_CHECKBOX));
		// cbVulumeMinimum.setChecked(loadCheckedState(AppInfo.KEY_VOLUME_MIN_CHECKBOX));
		etAlertMin.setText(getStringData(AppInfo.KEY_ALERT_MINUTES_STRING));
		etAlertSec.setText(getStringData(AppInfo.KEY_ALERT_SECOND_STRING));
		etPassword.setText(getStringData(AppInfo.KEY_PASSWORD));
		try {
			int a = getIntegerData(AppInfo.KEY_DIAL_ATTEMPTS_KEY);
			etDialingAttempts.setText(""+getIntegerData(AppInfo.KEY_DIAL_ATTEMPTS_KEY));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			etDialingAttempts.setText(""+0);
		}
		try {
			 
			SharedPreferences setting = this.getSharedPreferences(AppInfo.APP_PREF,0);
			etSecondsBeforeDialingAgain.setText(""+setting.getInt(AppInfo.KEY_SECONDS_BEFORE_DIALING_AGAIN, 1));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			etSecondsBeforeDialingAgain.setText(""+0);
		}
		try {
			String text = getStringData(AppInfo.KEY_MESSAGE_TEXT);
			etMessage.setText(getStringData(AppInfo.KEY_MESSAGE_TEXT));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			etMessage.setText("Defult message ");
		}

		cbEnablePass.setOnCheckedChangeListener(SetUpActivity.this);
		cbEnableAlert.setOnCheckedChangeListener(SetUpActivity.this);
		cbOpenSpeaker.setOnCheckedChangeListener(SetUpActivity.this);

		etAlertMin.setKeyListener(null);
		etAlertMin.setTag("Minutes");
		etAlertMin.setOnClickListener(this);
		etAlertSec.setKeyListener(null);
		etAlertSec.setTag("Seconds");
		etAlertSec.setOnClickListener(this);

		etPassword.setTypeface(typeface);
		etAlertSec.setTypeface(typeface);
		etAlertMin.setTypeface(typeface);
		etDialingAttempts.setTypeface(typeface);
		etSecondsBeforeDialingAgain.setTypeface(typeface);
		btnSave.setTypeface(typeface);




		// setting the font style of text
		TextView tvCallReminder 		= (TextView) this.findViewById(R.id.txt_call_reminder);
		TextView tvAlertMebeforeDialing		= (TextView) this.findViewById(R.id.txt_alert_me_before_dialing);
		TextView txt_time_of_alert 		= (TextView) this.findViewById(R.id.txt_time_of_alert);
		TextView txt_dialing_setup 		= (TextView) this.findViewById(R.id.txt_dialing_setup);
		TextView txt_rings_before_dialing 		= (TextView) this.findViewById(R.id.txt_rings_before_dialing);
		TextView txt_dialing_attempts_before_texting 		= (TextView) this.findViewById(R.id.txt_dialing_attempts_before_texting);
		TextView txt_text_message 		= (TextView) this.findViewById(R.id.txt_text_message);
		TextView txt_phone_after_call_starts 		= (TextView) this.findViewById(R.id.txt_phone_after_call_starts);
		TextView txt_open_speaker 		= (TextView) this.findViewById(R.id.txt_open_speaker);
		TextView txt_volume 		= (TextView) this.findViewById(R.id.txt_volume);
		TextView txt_volume_min 		= (TextView) this.findViewById(R.id.txt_volume_min);
		TextView txt_volume_max 		= (TextView) this.findViewById(R.id.txt_volume_max);
		TextView txt_password_title 		= (TextView) this.findViewById(R.id.txt_password_title);
		TextView txt_password_label 		= (TextView) this.findViewById(R.id.txt_password_label);
		tvCallReminder.setTypeface(typeface);
		tvAlertMebeforeDialing.setTypeface(typeface);
		txt_time_of_alert.setTypeface(typeface);
		txt_dialing_setup.setTypeface(typeface);
		txt_rings_before_dialing.setTypeface(typeface);
		txt_dialing_attempts_before_texting.setTypeface(typeface);
		txt_text_message.setTypeface(typeface);
		txt_phone_after_call_starts.setTypeface(typeface);
		txt_open_speaker.setTypeface(typeface);
		txt_volume.setTypeface(typeface);
		txt_volume_max.setTypeface(typeface);
		txt_volume_min.setTypeface(typeface);
		txt_password_title.setTypeface(typeface);
		txt_password_label.setTypeface(typeface);




		boolean isSpeaker = getCheckedState(AppInfo.KEY_OPEN_SPEAKER_CHECKBOX);
		for (int i = 0; i < rgVolume.getChildCount(); i = i + 2) {
			((RadioButton) rgVolume.getChildAt(i)).setEnabled(isSpeaker);
		}

		rbVolumeMaximum
		.setChecked(getCheckedState(AppInfo.KEY_OPEN_SPEAKER_RB_MAX));
		rbVolumeMinimum
		.setChecked(getCheckedState(AppInfo.KEY_OPEN_SPEAKER_RB_MIN));

		rbVolumeMaximum.setOnCheckedChangeListener(this);
		rbVolumeMinimum.setOnCheckedChangeListener(this);

		// cbVolumeMaximum.setOnCheckedChangeListener(SetUpActivity.this);
		// cbVulumeMinimum.setOnCheckedChangeListener(SetUpActivity.this);

	}

	private void setNullAlertData() {
		saveInPrefrences(AppInfo.KEY_ALERT_MINUTES_STRING, "");
		saveInPrefrences(AppInfo.KEY_ALERT_SECOND_STRING, "");
		saveInIntegerPrefrences(AppInfo.KEY_TOTAL_ALERT_TIME, 0);

	}

	private void saveAlertData() {
		String alertMinutes = etAlertMin.getText().toString();
		String alertSeconds = etAlertSec.getText().toString();

		if (isInputValid(alertMinutes, alertSeconds)) {

			int min = Integer.parseInt(alertMinutes);
			int second = Integer.parseInt(alertSeconds);
			int totalSecondsForAlert = min * 60 + second;
			saveInPrefrences(AppInfo.KEY_ALERT_MINUTES_STRING, alertMinutes);
			saveInPrefrences(AppInfo.KEY_ALERT_SECOND_STRING, alertSeconds);
			saveInIntegerPrefrences(AppInfo.KEY_TOTAL_ALERT_TIME,
					totalSecondsForAlert);
			AppInfo.ALART_TIME = totalSecondsForAlert;

			// start the alert timer

		} else {
			showToast("Please enter valid time");
		}

	}

	private boolean isInputValid(String minStr, String secStr) {
		int minutes = 0;
		int seconds = 0;
		try {
			minutes = Integer.parseInt(minStr);
			seconds = Integer.parseInt(secStr);
		} catch (Exception e) {
			Log.e(LOG_TAG, "Parsing Eception ::" + e.getMessage());
		}
		if (minStr.trim().length() < 1 || minutes >= 60) {
			return false;

		} else if (secStr.trim().length() < 1 || seconds >= 60) {
			return false;

		} else {
			return true;
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.cb_enable_password:
			save(isChecked, AppInfo.KEY_PASS_CHECKBOX);
			break;

		case R.id.cb_enable_alert:
			save(isChecked, AppInfo.KEY_ALERT_CHECKBOX);
			break;
		case R.id.cb_open_speaker:
			save(isChecked, AppInfo.KEY_OPEN_SPEAKER_CHECKBOX);
			for (int i = 0; i < rgVolume.getChildCount(); i = i + 2) {
				((RadioButton) rgVolume.getChildAt(i)).setEnabled(isChecked);
			}
			break;

		case R.id.cb_volume_maximum:
			save(isChecked, AppInfo.KEY_OPEN_SPEAKER_RB_MAX);

			break;

		case R.id.cb_volume_minimum:
			save(isChecked, AppInfo.KEY_OPEN_SPEAKER_RB_MIN);

			break;

			/*
			 * case R.id.cb_volume_maximum: if (cbVulumeMinimum.isChecked()) {
			 * cbVulumeMinimum.setChecked(false); cbVolumeMaximum.setChecked(true);
			 * }
			 * 
			 * 
			 * //save(isChecked,AppInfo.KEY_VOLUME_MAX_CHECKBOX); break;
			 * 
			 * case R.id.cb_volume_minimum: if (cbVolumeMaximum.isChecked()) {
			 * cbVulumeMinimum.setChecked(true); cbVolumeMaximum.setChecked(false);
			 * } //save(isChecked,AppInfo.KEY_VOLUME_MIN_CHECKBOX); break;
			 */

		default:
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		SubMenu langMenu = menu.addSubMenu(0, 200, 2, "NL-FR").setIcon(
				android.R.drawable.ic_menu_rotate);
		langMenu.add(1, 201, 0, R.string.fran_ais);
		langMenu.add(1, 202, 0, R.string.japan);
		langMenu.add(1, 203, 0, R.string.arabic);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case 201:

			Locale locale = new Locale("fr");
			Locale.setDefault(locale);
			Configuration config = new Configuration();
			config.locale = locale;
			getBaseContext().getResources().updateConfiguration(config,
					getBaseContext().getResources().getDisplayMetrics());
			Toast.makeText(this, R.string.locale_in_fran_ais_,
					Toast.LENGTH_LONG).show();
			break;

		case 202:

			Locale locale2 = new Locale("ja");
			Locale.setDefault(locale2);
			Configuration config2 = new Configuration();
			config2.locale = locale2;
			getBaseContext().getResources().updateConfiguration(config2,
					getBaseContext().getResources().getDisplayMetrics());

			Toast.makeText(this, R.string.locale_en_japanies_,
					Toast.LENGTH_LONG).show();
			break;
		case 203:

			Locale locale3 = new Locale("ar");
			Locale.setDefault(locale3);
			Configuration config3 = new Configuration();
			config3.locale = locale3;
			getBaseContext().getResources().updateConfiguration(config3,
					getBaseContext().getResources().getDisplayMetrics());

			Toast.makeText(this, R.string.locale_en_arabic_, Toast.LENGTH_LONG)
			.show();
			break;

		}
		return super.onOptionsItemSelected(item);
	}

	// method for saving string data in shared preferences
	private void saveInPrefrences(String key, String value) {
		SharedPreferences setting = this.getSharedPreferences(AppInfo.APP_PREF,
				0);
		Editor editor = setting.edit();
		editor.putString(key, value);
		editor.commit();
	}

	// method for saving string integer data in shared preferences
	private void saveInIntegerPrefrences(String key, int value) {
		SharedPreferences setting = this.getSharedPreferences(AppInfo.APP_PREF,
				0);
		Editor editor = setting.edit();
		editor.putInt(key, value);
		editor.commit();
	}

	// save the state of check box in preferences
	private void save(final boolean isChecked, String key) {
		SharedPreferences setting = this.getSharedPreferences(AppInfo.APP_PREF,
				0);
		SharedPreferences.Editor editor = setting.edit();
		editor.putBoolean(key, isChecked);
		editor.commit();
	}

	// getting the check box state from preferences
	private boolean getCheckedState(String key) {
		SharedPreferences setting = this.getSharedPreferences(AppInfo.APP_PREF,
				0);
		return setting.getBoolean(key, false);
	}

	// getting the string data from preferences
	private String getStringData(String key) {
		SharedPreferences setting = this.getSharedPreferences(AppInfo.APP_PREF,
				0);
		return setting.getString(key, "");
	}

	// getting the Integer data from preferences
	private int getIntegerData(String key) {
		SharedPreferences setting = this.getSharedPreferences(AppInfo.APP_PREF,
				0);
		return setting.getInt(key, 0);
	}

	// toast
	private void showToast(String message) {
		Toast.makeText(SetUpActivity.this, message, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.et_alert_min:

			setDialogValue(v);
			break;
		case R.id.et_alert_sec:

			setDialogValue(v);

			break;

		case R.id.button_setup_home:

			/*Intent intent = new Intent(v.getContext(), MainActivity.class);
			startActivity(intent);*/
			finish();

			break;
		case R.id.button_save_settings:

			saveSettingOnSave();

			break;

		case R.id.button_setup_whatis:

			Intent intent1 = new Intent(v.getContext(), WhatIsActivity.class);
			startActivity(intent1);
			finish();

			break;

		case R.id.et_dialing_attemptes:
			v.setTag("Diaing attemptes");
			showListDialog(v);


			break;
		case R.id.et_seconds_before_dialing:

			v.setTag("Seconds before dialing again");

			showListDialog(v);
			break;
		default:
			break;
		}
	}

	private void showListDialog(final View v) {
		// TODO Auto-generated method stub

		AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
		builder.setTitle(v.getTag().toString());
		String [] items = null;
		if (v.getId() == R.id.et_dialing_attemptes) {
			  items = new String[21];
			for (int i = 0; i < items.length; i++) {
				items[i] = ""+(i);

			}
		}
		if (v.getId() == R.id.et_seconds_before_dialing) {
			  items = new String[20];
			for (int i = 0; i < items.length; i++) {
				items[i] = ""+(i+1);

			}
		}
		
		final String[] calcuatedItems = items;
		builder.setItems(calcuatedItems  , new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub

				((EditText)v).setText(calcuatedItems[which]);

				if (v.getId() == R.id.et_dialing_attemptes) {

					SharedPreferences setting = getSharedPreferences(AppInfo.APP_PREF, 0);
					Editor editor = setting.edit();
					editor.putInt(AppInfo.KEY_DIAL_ATTEMPTS_KEY, which);
					editor.commit();
				}
				if (v.getId() == R.id.et_seconds_before_dialing) {
					SharedPreferences setting = getSharedPreferences(AppInfo.APP_PREF, 0);
					Editor editor = setting.edit();
					editor.putInt(AppInfo.KEY_SECONDS_BEFORE_DIALING_AGAIN, which+1);
					editor.commit();
				}
			}
		});
		builder.create().show();

	}

	private void saveSettingOnSave() {
		// TODO Auto-generated method stub
		boolean FLAG_PASS = true;
		boolean FLAG_ALERT = false;
		boolean FLAG_MSG = false;


		String password = etPassword.getText().toString();

		if (getCheckedState(AppInfo.KEY_PASS_CHECKBOX)) {
			if (password.trim().length() < 1) {
				showToast("Please enter the password ");
				etPassword.setError("Please enter the password");
				FLAG_PASS = false;

			} else {
				saveInPrefrences(AppInfo.KEY_PASSWORD, password);
				FLAG_PASS = true;
			}
		}

		// validation for spaeaker
		if (getCheckedState(AppInfo.KEY_OPEN_SPEAKER_CHECKBOX)) {

		}
		int totalDialTime = getIntegerData(AppInfo.KEY_TOTAL_DIAL_TIME);
		int totalAlertTime = getIntegerData(AppInfo.KEY_TOTAL_ALERT_TIME);
		Log.d(LOG_TAG, "totalAlertTime :::" + totalAlertTime);
		Log.d(LOG_TAG, "totalDialTime :::" + totalDialTime);

		// Validation for password alert check
		if (getCheckedState(AppInfo.KEY_ALERT_CHECKBOX)) {
			if (totalDialTime == 0 && totalAlertTime == 0) {
				saveAlertData();
				FLAG_ALERT = true;

			}

			else if (totalAlertTime == 0 && totalDialTime > totalAlertTime) {
				saveAlertData();
				FLAG_ALERT = true;

			} else if (totalDialTime != 0 && totalDialTime > totalAlertTime) {
				saveAlertData();
				FLAG_ALERT = true;

			} else {
				showToast("enter valid time");
				FLAG_ALERT = false;

			}
		} else {
			setNullAlertData();
			FLAG_ALERT = true;
			
			
			
		}

		/*	String dialAttemptsText = etDialingAttempts.getText().toString();
		dialAttemptsText = dialAttemptsText.length()==0?"0":dialAttemptsText;
		 */

		if (etMessage.getText().toString().trim().length()>0) {
			FLAG_MSG = true;

			SharedPreferences setting = getSharedPreferences(AppInfo.APP_PREF, 0);
			Editor editor = setting.edit();
			editor.putString(AppInfo.KEY_MESSAGE_TEXT, etMessage.getText().toString());
			editor.commit();
		} else {
			FLAG_MSG = false;
			etMessage.setError("Enter a message");
		}

		if (FLAG_PASS && FLAG_ALERT && FLAG_MSG) {

			showToast("Settings are saved");
			finish();
		}

	}

	protected void setDialogValue(final View v) {
		// TODO Auto-generated method stub

		AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
		builder.setTitle(v.getTag().toString());
		final String[] items = new String[60];
		for (int i = 0; i < items.length; i++) {
			items[i] = "" + i;
		}
		builder.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				((EditText) v).setText(items[which]);
			}
		});
		builder.create().show();
	}

}